<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>{{ isEdit ? '编辑章节' : '新增章节' }}</span>
        </div>
      </template>

      <el-form
        ref="chapterFormRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="max-width: 600px"
      >
        <el-form-item label="章节名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入章节名称" />
        </el-form-item>
        
        <el-form-item label="所属课程" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请选择课程" clearable>
            <el-option
              v-for="item in courseOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="form.sort"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getChapterById, saveOrUpdateChapter } from '@/api/chapter'

// 路由相关
const route = useRoute()
const router = useRouter()

// 表单引用
const chapterFormRef = ref()

// 是否为编辑模式
const isEdit = ref(false)

// 课程选项
const courseOptions = ref([])

// 表单数据
const form = reactive({
  id: undefined,
  name: '',
  courseId: '',
  sort: 0
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入章节名称', trigger: 'blur' }],
  courseId: [{ required: true, message: '请选择所属课程', trigger: 'blur' }]
}

// 获取课程选项数据
const getCourseOptions = async () => {
  // 这里需要调用相应的API获取选项数据
  // 暂时使用模拟数据
  courseOptions.value = [
    { id: 1, name: 'Java程序设计' },
    { id: 2, name: 'Python数据分析' }
  ]
}

// 获取章节详情
const getChapterDetail = async (id) => {
  try {
    const response = await getChapterById(id)
    Object.assign(form, response.data)
  } catch (error) {
    ElMessage.error('获取章节信息失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!chapterFormRef.value) return
  
  await chapterFormRef.value.validate((valid) => {
    if (valid) {
      saveOrUpdateChapter(form)
        .then(() => {
          ElMessage.success('保存成功')
          goBack()
        })
        .catch(() => {
          ElMessage.error('保存失败')
        })
    }
  })
}

// 返回上一页
const goBack = () => {
  router.push('/chapters')
}

// 初始化
onMounted(() => {
  getCourseOptions()
  
  // 判断是否为编辑模式
  if (route.params.id) {
    isEdit.value = true
    getChapterDetail(route.params.id)
  }
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>